<!--#include file="config.asp"-->
<%
''' SDCMS 新浪微博登录
''' ==================================================================
''' 版权所有 http://www.sdcms.cn
''' ------------------------------------------------------------------
''' 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用；
''' 未经授权不允许对程序代码以任何形式任何目的的再发布。
''' ==================================================================
''' 编写: IT平民
''' 修改：IT平民 in 2014.08

	sub callback()
		dim code:code=sdcms.enhtml(sdcms.fget("code",0))

		if sdcms.strlen(code)=0 then
			sdcms.echo "非法参数传递，无法登录"
			exit sub
		end if
		
		dim url
		url="https://api.weibo.com/oauth2/access_token?"
		url=url&"client_id="&weibo_appid
		url=url&"&client_secret="&weibo_appkey
		url=url&"&grant_type=authorization_code"
		url=url&"&code="&code
		url=url&"&redirect_uri="&callbackurl

		dim str:str=sdcms.gethttp(url,"post")
		dim json
		set json=toobject(str)
		if instr(str,"error_code")>0 then
			sdcms.echo "错误编号："&sdcms.enhtml(json.error_code)&"<br>"
			sdcms.echo "错误原因："&sdcms.enhtml(json.error_description)&"<br>"
			exit sub
		else
			dim token:token=json.access_token
			openid=json.uid
			sdcms.setsession "token",token
			sdcms.setsession "openid",openid
		end if
		set json=nothing
	end sub
	
	sub get_openid()
		dim gourl:gourl=sdcms.loadsession("api_backurl")
			dim data:data=sdcms.db.dbload(1,"n.userid,u.logintimes","sd_user_bind n left join sd_user u on n.userid=u.id","n.openid='"&openid&"' and n.opentype='weibo'","")
			if ubound(data)<0 then
				sdcms.setsession "api_backurl",""
				sdcms.go "bind.asp?api_backurl="&gourl
				exit sub
			else
				sdcms.db.dbupdate "sd_user","id="&data(0,0)&"",array(array("logintimes",data(1,0)+1,0,0))
				sdcms.resetuserinfo("u.id="&data(0,0)&"")
				sdcms.setsession "openid",""
				sdcms.setsession "api_backurl",""
				sdcms.setsession "token",""
				if sdcms.strlen(gourl)=0 then gourl=webroot
				sdcms.go gourl
			end if
	end sub
	dim openid
	callback()
	get_openid()
%>